package com.fz.us.admin.base.bean.search.rule;

import com.fz.us.admin.base.bean.search.SearchEnum;
import com.fz.us.admin.base.utils.CommonUtil;
import org.hibernate.criterion.MatchMode;
import org.springframework.util.Assert;

/**
 * 查询 - 参数 - RuleLike
 * ============================================================================
 * 版权所有 2016 。
 *
 * @author fallenpanda
 * @version 1.0 2016-07-13 。
 * ============================================================================
 */
public class RuleLike extends Rule {

    private final String field;
    private final Object data;
    private final MatchMode matchMode;

    private RuleLike(SearchEnum.RuleType ruleType, String field, Object data, MatchMode matchMode) {
        super(ruleType);
        this.field = field;
        this.data = data;
        this.matchMode = matchMode;
    }

    public String getField() {
        return field;
    }

    public Object getData() {
        return data;
    }

    public MatchMode getMatchMode() {
        return matchMode;
    }

    public static RuleLike like(String field, Object data) {
        return newBuilder().setRuleType(SearchEnum.RuleType.like).setField(field).setData(data).build();
    }

    public static RuleLike like(String field, String data, MatchMode matchMode) {
        return newBuilder().setRuleType(SearchEnum.RuleType.like).setField(field).setData(data).setMatchMode(matchMode).build();
    }

    public static RuleLike ilike(String field, Object data) {
        return newBuilder().setRuleType(SearchEnum.RuleType.ilike).setField(field).setData(data).build();
    }

    public static RuleLike ilike(String field, String data, MatchMode matchMode) {
        return newBuilder().setRuleType(SearchEnum.RuleType.ilike).setField(field).setData(data).setMatchMode(matchMode).build();
    }

    public static Builder newBuilder() {
        return new Builder();
    }

    public static class Builder extends Rule.Builder<Rule, Builder> {

        private String field;
        private Object data;
        private MatchMode matchMode;

        @Override
        protected Builder getThis() {
            return this;
        }

        public Builder setField(String field) {
            this.field = field;
            return this;
        }

        public Builder setData(Object data) {
            this.data = data;
            return this;
        }

        public Builder setMatchMode(MatchMode matchMode) {
            this.matchMode = matchMode;
            return this;
        }

        @Override
        public RuleLike build() {
            Assert.notNull(ruleType, "ruleType 不能为空");
            Assert.hasText(field, "field 不能为空");
            Assert.notNull(data, "data 不能为空");
            Assert.isTrue(CommonUtil.isField(field), "field 非法参数");
            return new RuleLike(ruleType, field, data, matchMode);
        }

    }

}
